<template>
  <div id="applicationConfim" class="person-detail">
    <div>
      <van-nav-bar title="申请确认" :fixed="true" left-arrow @click-left="back" />
    </div>
    <van-cell-group>
      <van-field label="服务名称" disabled v-model="value1" />
      <van-field label="申请人" v-model="value2" placeholder="请输入申请人姓名" />
      <van-field label="联系电话" v-model="value3" placeholder="请输入手机号" />
      <van-field v-model="value4" placeholder="请详细描述申请原由..." type="textarea" maxlength="100" rows="5" show-word-limit
        autosize />
    </van-cell-group>
    <div class="downloadmoban">先点击下方材料下载模板,按照提供的材料编写所需资料然后拍照上传,请严格按照材料顺序并且数量和材料数量相等上传,否则可能导致申请失败</div>
    <div class="applicationConfim-download" v-for="(item,index) in downloadData" :key="index">
      <div style="display:flex;">
        <p @click="download(index)">
          <van-icon name="plus" />
          {{item.attachmentName}}:{{item.fileName}}
        </p>
      </div>
    </div>
    <div class="applicationConfim-upload">
      <van-uploader v-model="imageList" :max-count="downloadData.length" multiple :after-read="onRead" />
    </div>
    <div class="mine-out">
      <van-button type="default" @click="confirm()">提交</van-button>
    </div>
  </div>
</template>
<script>
  import mine from "@/controller/mine.js"
  import util from "@/controller/Common/util.js"
  import {
    Dialog
  } from 'vant'
  export default {
    name: 'applicationConfim',
    components: {},
    data() {
      return {
        value1: JSON.parse(localStorage['specialService']).app_name,
        value2: '',
        value3: '',
        value4: '',
        imageList: [],
        downloadData: JSON.parse(localStorage['specialService']).data.attachments,
        uploadList: [],
        fileList: []
      }
    },
    computed: {},
    created() {},
    mounted() {},
    watch: {
      onSuccess: function (imageData) {
        this.imgData = "data:image/jpeg;base64," + imageData;
      },
      onFail: function (message) {
        alert("Failed because: " + message);
      }
    },
    methods: {
      onRead(file) {
        let isArray = Object.prototype.toString.call(file) === "[object Array]";
        if (isArray && file.length > 7) {
          this.$toast("最多上传7张图片");
          return;
        }
        if (isArray) {
          this.imageList.push(file);
        }
        this.upload()
      },
      upload() {
        if (this.imageList[0].content != this.avatar) {
          let imgUploader = [];
          this.imageList.map(v => {
            let formData = new FormData();
            formData.append("file", v.file);
            imgUploader.push(
              mine.upload_image(formData).then(res => {
                if (res.data.code == "0") {
                  v.url = res.data.datas;
                } else {
                  this.$toast(res.data.msg);
                }
              })
            );
          });
          Promise.all(imgUploader).then(() => {
            //let that = this

            //data = { "headImg" : that.imageList[0].url };
            if (this.downloadData.length != this.imageList.length) {
              this.$toast("请务必照片与下载文档数量,顺序一致!")
            } else if (this.downloadData.length == this.imageList.length) {
              this.downloadData.forEach((item, index) => {
                let data = {
                  attachmentName: item.attachmentName,
                  attachmentUrl: this.imageList[index].url,
                  fileName: item.fileName
                }
                this.fileList.push(data)
              })
            }
          });
        }
      },
      download(index) {
        document.addEventListener("deviceready", this.downloadFun(index).bind(this), false);
        //     let arr = JSON.parse(localStorage['specialService']).data.attachments[index].attachmentUrl
        //      let link = document.createElement('a')
        //   link.href = arr
        //   link.download = JSON.parse(localStorage['specialService']).data.attachments[index].fileName
        //   link.click()
        //释放内存
        // window.location.href = arr
      },
      downloadFun(index) {
        let _this = this;
        // eslint-disable-next-line no-undef
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
          fs.root.getFile(JSON.parse(localStorage['specialService']).data.attachments[index].fileName, {
            create: true,
            exclusive: false
          }, function (fileEntry) {
            _this.downLoadImg(fileEntry.nativeURL, index);
          }, function () {});
        }, function () {});
      },

      downLoadImg(fileURL, index) {
        // 初始化FileTransfer对象
        // eslint-disable-next-line no-undef
        let fileTransfer = new FileTransfer();
        // 服务器下载地址
        let uri = encodeURI(JSON.parse(localStorage['specialService']).data.attachments[index].attachmentUrl);
        // 调用download方法
        fileTransfer.download(
          uri, //uri网络下载路径
          fileURL, //url本地存储路径
          function () {
            Dialog({
              message: '请在手机文件管理/内部存储的根目录下查找刚才下载的文件'
            })
          },
          function () {
            Dialog({
              message: '文件下载失败'
            })
          }
        );
      },

      confirm() {
        if (this.value2 == '' || this.value3 == '' || this.value4 == '') {
          this.$toast("输入不能为空")
          return
        }
        if (!util.validatePhoneNum(this.value3)) {
          return this.$toast("请输入正确的手机号")
        }
        if (this.downloadData.length != this.imageList.length) {
          this.$toast("请务必上传照片与下载文档数量,顺序一致!")
          return
        }
        let data = {
          "applyUser": this.value2,
          "contactPhone": this.value3.toString(),
          "reason": this.value4,
          "serviceId": JSON.parse(localStorage['specialService']).id,
          "applyAttachments": this.fileList
        }
        mine.spServiceApply_v1_create(data).then(res => {
          if (res.code == '0') {
            this.$toast.success('申请成功!')
            setTimeout(() => {
              this.$router.push({
                path: '/work/specialService/myServiceApplication'
              })
            }, 1000);
          } else {
            this.$toast(res.msg)
          }
        })
      },
      back() {
        this.$router.go(-1)
      },
    }
  }
</script>
<style lang="scss" scoped>
  #applicationConfim {
    background: #fff;

    .downloadmoban {
      padding: 10px 20px;
      opacity: .7;
      font-size: 14px;
    }

    .mine-out {
      padding: 50px 0;
      position: fixed;
      width: 100%;
      top: 85%;

      button {
        width: 80%;
        height: 80%;
        margin: auto;
        display: block;
        font-size: 20px;
        color: #fff;
        letter-spacing: 0;
        text-align: center;
        background: #DC4630;
        border-radius: 20px;
      }
    }
  }
</style>
<style lang="scss">
  #applicationConfim {
    .applicationConfim-download {
      >div:nth-child(1) {
        >p {
          line-height: 28px;
          width: 250px;
          margin-top: 10px;
          font-size: 14px;
          padding: 0 20px;

          >i {
            top: 4px;
            font-size: 18px !important;
            font-weight: bold;
          }
        }
      }
    }

    .applicationConfim-upload {
      padding: 10px;
    }

    textarea.van-field__control {
      background-color: #F5F5F5;
      border-radius: 4px;
      padding: 5px;
    }
  }
</style>